﻿create PROCEDURE Sync.SP_LoanCases_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanCases_Temp TABLE 
		(
			LoanCaseID UniqueIdentifier,
			[LoanID] uniqueidentifier,
				[CaseNumber] bigint,
				[CaseDate] datetime,
				[Notes] nvarchar(MAX),
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanCases_Temp 
	   SELECT	Tbl.Col.value('LoanCaseID[1]','uniqueidentifier') LoanCaseID,
                Tbl.Col.value('LoanID[1]', 'uniqueidentifier') [LoanID],
Tbl.Col.value('CaseNumber[1]', 'bigint') [CaseNumber],
Tbl.Col.value('CaseDate[1]', 'datetime') [CaseDate],
Tbl.Col.value('Notes[1]', 'nvarchar(MAX)') [Notes],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanCases') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanCases] ([LoanCaseID],[LoanID],[CaseNumber],[CaseDate],[Notes])
	SELECT t.[LoanCaseID],t.[LoanID],t.[CaseNumber],t.[CaseDate],t.[Notes]
	FROM  @LoanCases_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanCases_Tracking s
        WHERE t.LoanCaseID = s.LoanCaseID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanCases]
	SET [LoanCases].[LoanID] = t.[LoanID],[LoanCases].[CaseNumber] = t.[CaseNumber],[LoanCases].[CaseDate] = t.[CaseDate],[LoanCases].[Notes] = t.[Notes] 
	FROM [dbo].[LoanCases] s JOIN @LoanCases_Temp t 
    ON t.LoanCaseID = s.LoanCaseID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanCases_Tracking r
				  WHERE t.LoanCaseID = r.LoanCaseID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanCases]
    FROM @LoanCases_Temp t JOIN [dbo].[LoanCases] s
    ON t.LoanCaseID = s.LoanCaseID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











